package com.xzlf.service.impl;

import com.xzlf.service.Cacheservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@CacheConfig()
public class CachsServiceImpl implements Cacheservice {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Override
    public String getInfo() {
        return null;
    }

    @Override
    @Cacheable(cacheNames = "testGet")
    public String testGet() {
        ServiceInstance si = loadBalancerClient.choose("application-service");
        StringBuffer sb = new StringBuffer();
        sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/").append("testGet");
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> exchange = restTemplate.exchange(sb.toString(), HttpMethod.GET, null, String.class);

        return exchange.getBody();
    }

    @Override
    @CacheEvict(cacheNames = "testGet")
    public String testPost() {
        ServiceInstance si = loadBalancerClient.choose("application-service");
        StringBuffer sb = new StringBuffer();
        sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/").append("testPost");
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> exchange = restTemplate.exchange(sb.toString(), HttpMethod.POST, null, String.class);

        return exchange.getBody();
    }
}
